package com.zb.emq;

import com.alibaba.fastjson.JSON;
import com.zb.dto.DeviceInfoDTO;
import com.zb.entity.TbQuotaModel;
import com.zb.service.DeviceService;
import com.zb.service.TbAlarmService;
import com.zb.service.TbQuotaService;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class EmqMessageProccess implements MqttCallback {
    @Autowired
    private EmqClient emqClient;
    @Autowired
    private TbQuotaService quotaService;
    @Autowired
    private TbAlarmService tbAlarmService;
    @Autowired
    private DeviceService deviceService;

    /**
     * 程序与mqtt服务断开连接， 重新建立连接的方法
     *
     * @param throwable
     */

    @Override
    public void connectionLost(Throwable throwable) {
        System.out.println("重新建立连接");
        emqClient.connect();
        List<TbQuotaModel> list = quotaService.list();
        list.forEach(item -> {
            emqClient.subscribe("$queue/"+item.getSubject());
        });
        System.out.println("订阅主题完毕");
    }
    /**
     * 订阅到消息之后，的监听方法,
     * 主题中有数据， 下面的方法自动执行
     *
     * @param mqttMessage
     * @throws Exception
     */

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        System.out.println("topic:"+topic);
        String msg = new String(mqttMessage.getPayload());
        System.out.println("监听的信息:"+msg);
        Map<String,Object> mapData = JSON.parseObject(msg,Map.class);
        //解析指标
        DeviceInfoDTO deviceInfoDTO = quotaService.analysis(topic, mapData);
        DeviceInfoDTO newDeviceInfo = tbAlarmService.verifyDeviceInfo(deviceInfoDTO);
        //添加设备
        boolean b = deviceService.saveDeviceInfo(newDeviceInfo.getDevice());
        if (b){
            quotaService.saveQuotaToInflux(newDeviceInfo.getQuotaList());
        }
        System.out.println(JSON.toJSONString(newDeviceInfo));
        System.out.println(b?"设置成功":"设置失败");
    }
    /**
     * 程序断开服务器自动触发的方法
     *
     * @param iMqttDeliveryToken
     */

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {

    }
}
